package com.neihanduanzi.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.neihanduanzi.BaseActivity;
import com.neihanduanzi.R;
import com.neihanduanzi.adapter.DuanZiListAdapter;
import com.neihanduanzi.api.DuanZiServer;
import com.neihanduanzi.database.DButil;
import com.neihanduanzi.database.DuanziDb;
import com.neihanduanzi.model.DuanZi;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class ZDuanziFragment extends BaseFragment implements AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {


    private View ret;
    private ListView mList;
    private List<DuanZi.Data> mData ;
    private DuanZiListAdapter mAdapter;
    private DuanZiServer mDuanZiServer;
    private DuanZi mduanzi;
    private SwipeRefreshLayout mRefreshLayout;


    public ZDuanziFragment() {
        // Required empty public constructor
    }

    @Override
    public String getFragmentTitle() {
        return "段子";
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mData = new ArrayList<>();
        mAdapter = new DuanZiListAdapter(getContext(), mData);

//        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        ret = inflater.inflate(R.layout.fragment_zduanzi, container, false);
        mList = (ListView)ret.findViewById(R.id.duanzi_list);
        mList.setAdapter(mAdapter);
        mRefreshLayout = (SwipeRefreshLayout)ret. findViewById(R.id.duanzi_refresh);
        mRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.pink));
        mRefreshLayout.setOnRefreshListener(this);

        initDatabase();
        initData();

        mList.setOnItemClickListener(this);

        return ret;
    }


    private void initDatabase() {
        List<DuanziDb> list1 = DButil.queryAllDuanzi();
        if (list1 != null) {
            resolve(list1.get(0).getGroup());
        }
    }

    private void initData() {
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl("http://ic.snssdk.com/neihan/");
        builder.addConverterFactory(ScalarsConverterFactory.create());
        Retrofit build = builder.build();
        mDuanZiServer = build.create(DuanZiServer.class);

        Call<String> duanZiList = mDuanZiServer.getDuanZiList();
        duanZiList.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()){
                    mRefreshLayout.setRefreshing(false);
                    String body = response.body();
                    if (body != null) {
                        DButil.deleteDuanzi();
                        DuanziDb duanziDb = new DuanziDb();
                        duanziDb.setGroup(body);
                        DButil.addData(duanziDb);
                    }
                    resolve(body);
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d("hah", "hhhhhhhhhhh");
            }
        });
    }

    private void resolve(String body) {
        if (body != null) {
            try {
                mData.clear();
                JSONObject json = new JSONObject(body);
                JSONObject jsonData = json.getJSONObject("data");
                String s = jsonData.toString();

                Gson gson = new Gson();
                DuanZi duanZi = gson.fromJson(jsonData.toString(), DuanZi.class);

                List<DuanZi.Data> data = duanZi.getData();
                mData.addAll(data);
                mAdapter.notifyDataSetChanged();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DuanZi.Data.Group group = mData.get(position).getGroup();
        Gson gson = new Gson();
        String str = gson.toJson(group);
        Intent intent = new Intent(getContext(), BaseActivity.class);
        intent.putExtra("Data", str);
        intent.putExtra("type",4);
        intent.putExtra("group_id",group.getGroup_id());
        startActivity(intent);

    }
    @Override
    public void onRefresh() {
        initData();
    }

    @Override
    public void onDestroy() {
//        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEvent(List<DuanZi.Data.Group> datas){
//         (String text, String imgUrl, String title, String titleUrl, String weixinUrl)
//        String content = datas.get(0).getContent();
//        String share_url = datas.get(0).getShare_url();
//        MainActivity activity;
//        activity = (MainActivity) (this.getActivity());
//        activity.showShare(content, null, null, null, share_url);
//
//    }
}
